// pages/fix/fix.js
var api = require('../../utils/api.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    resData: {},
    cell: "",
    message: "", // 其他
    touch: true, // 防止多次点击
    resData: {}, //请求数据
    value: null, // 骑车年限
    battery: null, // 电池规格
    years: [], // 年限列表
    cell: [], // 电池列表
    fileList: [], // 存放图片
    showPicker: false,
    showPickers: false,
    showPopup: false,
    type: "", // 判断应急 预约
    index: null, // 下标
    minDate: new Date(2020, 0, 1).getTime(),
    maxDate: new Date(2025, 10, 1).getTime(),
    currentDate: new Date().getTime(),
    todayTimes: "",
    i: null, // 年限下标
    attr_id: "",
    http: true,
    delete: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)

    if (options.type == '1') {
      this.setData({
        type: 2
      })
    } else {
      this.setData({
        type: 1
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  forData(newArr, data) {
    data.forEach(item => {
      newArr.push(item.des)
    })
    return newArr
  },

  regRule(param) {
    let msg
    let emotion = /([^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n])|(\s)/g
    let content = /[@#$%^&*]+/g
    if (emotion.test(param)) {
      return msg = '禁止输入表情符/颜文字等非法字符'
    } else if (content.test(param)) {
      return msg = '输入内容有误'
    } else if (!param) {
      return msg = '内容不能为空'
    } else {
      return msg = ''
    }
  },

  confirm() {
    let arrImg = []
    if (this.data.resData.addr.length == 0) {
      wx.showToast({
        title: '请先添加维修地址!',
        icon: 'none'
      })
    } else if (this.data.index == null) {
      wx.showToast({
        title: '请选择电瓶车问题!',
        icon: 'none'
      })
    } else if (this.data.value == null) {
      wx.showToast({
        title: '请选择电瓶车年限!',
        icon: 'none'
      })
    } else if (this.data.battery == null) {
      wx.showToast({
        title: '请选择电池规格!',
        icon: 'none'
      })
    } else if (this.data.fileList.length == "0") {
      wx.showToast({
        title: '请上传车辆照片!',
        icon: 'none'
      })
    } else {
      if (this.regRule(this.data.message)) {
        wx.showToast({
          title: this.regRule(this.data.message),
          icon: 'none'
        })
      } else {
        if (this.data.type == "1") {
          if (this.data.todayTimes == null) {
            wx.showToast({
              title: '请选择预约时间!',
              icon: 'none'
            })
            return
          }
        }

        this.data.fileList.forEach(item => {
          arrImg.push(item.url)
        })

        let data = {
          userid_locked: wx.getStorageSync('userid_locked'),
          remark: this.data.message,
          address_id: this.data.resData.addr.address_id,
          sign: this.data.resData.question[this.data.index].sign, // 维修标识符
          year: this.data.resData.list_year[this.data.i].year, // 年份
          img: JSON.stringify(arrImg), // 图片
          attr_id: this.data.attr_id, // 电池规格
          type: this.data.type, // 订单类型
          appoint_id: this.data.resData.last_des.appoint_id ? this.data.resData.last_des.appoint_id : 0 // 预约id
        };

        if (this.data.type == "1") {
          data.appoint_time = this.data.todayTimes // 预约时间
        }

        if (this.data.touch) {
          this.setData({
            touch: false
          })
          api.form_('Serve_car/submit_appoint', data, null, (res) => {
              console.log(res.data)
              // 预约
              if (this.data.type == "1") {
                if (res.data.result_code == "308") {
                  wx.showToast({
                    title: res.data.msg,
                    icon: 'none',
                  })
                  this.setData({
                    http: true
                  })
                  setTimeout(() => {
                    wx.navigateTo({
                      url: `../payment/payment?type=${this.data.type}&orderId=${res.data.data.apponit_id}`
                    })
                  }, 1000)
                } else {
                  this.setData({
                    http: true
                  })
                  wx.showToast({
                    title: res.data.msg,
                    icon: 'none'
                  })
                }
                // 紧急
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none'
                })
                this.setData({
                  http: true
                })
                setTimeout(() => {
                  wx.reLaunch({
                    url: '../home/home',
                  })
                }, 1000)
              }
            },
            (err) => {
              console.log(err)
              this.setData({
                http: true
              })
              wx.showToast({
                title: err.data.msg,
                icon: 'none'
              })
            })
          setTimeout(() => {
            this.setData({
              touch: true
            })
          }, 3000)
        } else {
          wx.showToast({
            title: '您点击的次数太快了!',
            icon: 'none'
          })
        }
      }
    }
  },

  one() {
    this.setData({
      showPicker: true
    })
  },
  ones() {
    this.setData({
      showPicker: false
    })
  },
  two() {
    this.setData({
      showPickers: true
    })
  },
  twos() {
    this.setData({
      showPickers: false
    })
  },
  three() {
    this.setData({
      showPickerd: true
    })
  },
  timePicker() {
    this.setData({
      showPopup: true
    })
  },
  timePickers() {
    this.setData({
      showPopup: false
    })
  },

  quest(e) {
    this.setData({
      index: e.currentTarget.dataset.index
    })
  },

  onConfirm(e) {
    this.setData({
      value: e.detail.value,
      i: e.detail.index,
      showPicker: false
    })
  },
  onConfirms(e) {
    // console.log(e.detail)
    this.setData({
      battery: e.detail.value,
      attr_id: this.data.resData.size[e.detail.index].attr_id,
      showPickers: false
    })
  },

  upload: function () {
    this.setData({
      http: false
    })
  },

  afterRead(event) {
    const {
      file
    } = event.detail;
    let count = 0;
    this.upImg(file, count);
  },

  upImg: function (file, count) {
    let that = this;
    wx.uploadFile({
      url: 'https://images.cd1a.cn/appoint_repair.php', //仅为示例，非真实的接口地址
      filePath: file[count].url,
      name: 'file',
      formData: {
        user_id: wx.getStorageSync('userid_locked')
      },
      success(res) {
        let result = JSON.parse(res.data)
        console.log(result)
        if (result.result_code == "205") {
          that.data.fileList.push({
            url: result.data[0]
          })
          that.setData({
            fileList: that.data.fileList,
          })

          count++;
          if (count == file.length) {
            count = 0;
            return;
          } else {
            that.upImg(file, count);
          }

        } else {
          wx.showToast({
            title: result.msg,
            icon: 'none'
          })
        }
      },
      fail(err) {
        wx.showToast({
          title: err.msg,
          icon: 'none'
        })
      }
    })
  },

  deleteImg(e) {
    let arrImg = this.data.fileList.filter((item, index) => index != e.detail.index)
    this.setData({
      delete: true,
      fileList: arrImg
    })
  },

  yes(e) {
    this.setData({
      showPopup: false,
      todayTimes: this.timeFormat(e.detail)
    })
  },

  timeFormat(value) {
    let time = new Date(value)
    let year = time.getFullYear()
    let month = time.getMonth() + 1
    let day = time.getDate()
    let hour = time.getHours()
    let minute = time.getMinutes()
    let second = time.getSeconds()
    return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    let newArr = []
    if (that.data.http) {
      api.form_('Serve_car/appoint', {
          userid_locked: wx.getStorageSync('userid_locked')
        },
        null,
        function success(res) {
          console.log(res.data)
          if (res.data.data) {
            if (res.data.data.last_des.length != 0) {
              let imgArr = JSON.parse(res.data.data.last_des.repair_img)
              imgArr.forEach(item => {
                newArr.push({
                  url: item
                })
              })
              that.setData({
                fileList: that.data.delete ? that.data.fileList : newArr,
                todayTimes: res.data.data.last_des.appoint_time,
                message: res.data.data.last_des.descript,
                index: res.data.data.last_des.repair_type - 1,
                value: res.data.data.last_des.use_year_des,
                battery: res.data.data.last_des.size,
                i: res.data.data.last_des.use_year - 1,
                attr_id: res.data.data.last_des.battery_type,
              })
            }
            that.setData({
              resData: res.data.data,
              years: that.forData([], res.data.data.list_year), // 年限
              cell: that.forData([], res.data.data.size) // 电池规格 
            })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: "none"
            })
          }
        },
        function fail(err) {
          console.log(err)
        }
      )
    }
  },

  contact() {
    if (this.data.resData.addr.length != 0) {
      wx.navigateTo({
        url: '../location/location?address_id=' + encodeURIComponent(JSON.stringify(this.data.resData.addr))
      })
    } else {
      wx.navigateTo({
        url: '../location/location'
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})